<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,100分)- 字符串变换最小字符串（Java & JS & Python & C）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>给定一个字符串s&#xff0c;最多只能进行一次变换&#xff0c;返回变换后能得到的最小字符串&#xff08;按照字典序进行比较&#xff09;。</p> 
<p>变换规则&#xff1a;交换字符串中任意两个不同位置的字符。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>一串小写字母组成的字符串s</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>按照要求进行变换得到的最小字符串。</p> 
<p></p> 
<h4>备注</h4> 
<ul><li>s是都是小写字符组成</li><li>1 ≤ s.length ≤ 1000</li></ul> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">abcdef</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">abcdef</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">abcdef已经是最小字符串&#xff0c;不需要交换。</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">bcdefa</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">acdefb</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">a和b进行位置交换&#xff0c;可以得到最小字符串</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>我的思路如下&#xff0c;先将输入的字符串str进行字典排序&#xff0c;得到一个新串minStr&#xff0c;如果str和minStr相同&#xff0c;则说明str已经是最小字符串&#xff0c;不需要任何变换&#xff0c;直接返回str。</p> 
<p>如果str和minStr不同&#xff0c;则说明str不是最小字符串&#xff0c;我们需要遍历出str的每一个字符&#xff0c;对比str[i] 和 minStr[i] &#xff0c;具体处理逻辑如下图</p> 
<p><img alt="" height="430" src="https://img-blog.csdnimg.cn/3e878c4af2134bd4bceae37246f7e82f.png" width="607" /></p> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);
    System.out.println(getResult(sc.nextLine()));
  }

  public static String getResult(String s) {
    char[] minSArr &#61; s.toCharArray();
    Arrays.sort(minSArr);

    String minS &#61; new String(minSArr);
    if (minS.equals(s)) return s;

    char[] sArr &#61; s.toCharArray();

    for (int i &#61; 0; i &lt; s.length(); i&#43;&#43;) {
      if (sArr[i] !&#61; minSArr[i]) {
        char tmp &#61; sArr[i];
        sArr[i] &#61; minSArr[i];

        int swapIndex &#61; s.lastIndexOf(minSArr[i]);
        sArr[swapIndex] &#61; tmp;
        break;
      }
    }

    return new String(sArr);
  }
}
</code></pre> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  console.log(getMinStrAfterOneSwap(line));
});

function getMinStrAfterOneSwap(str) {
  const minStrArr &#61; [...str].sort();
  if (str &#61;&#61;&#61; minStrArr.join(&#34;&#34;)) return str;

  const strArr &#61; [...str];

  for (let i &#61; 0; i &lt; strArr.length; i&#43;&#43;) {
    if (strArr[i] !&#61;&#61; minStrArr[i]) {
      let tmp &#61; strArr[i];
      strArr[i] &#61; minStrArr[i];

      let swapIndex &#61; str.lastIndexOf(minStrArr[i]);
      strArr[swapIndex] &#61; tmp;
      break;
    }
  }

  return strArr.join(&#34;&#34;);
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
s &#61; input()


# 算法入口
def getResult():
    minSArr &#61; list(s)
    minSArr.sort()

    if s &#61;&#61; &#34;&#34;.join(minSArr):
        return s

    sArr &#61; list(s)

    for i in range(len(s)):
        if sArr[i] !&#61; minSArr[i]:
            tmp &#61; sArr[i]
            sArr[i] &#61; minSArr[i]

            swapIdx &#61; s.rindex(minSArr[i])
            sArr[swapIdx] &#61; tmp
            break

    return &#34;&#34;.join(sArr)


# 调用算法
print(getResult())</code></pre> 
<p></p> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

#define MAX_SIZE 1000

char *getResult(char s[]);

int main() {
    char s[MAX_SIZE];
    gets(s);

    puts(getResult(s));

    return 0;
}

int cmp(const void *a, const void *b) {
    return (*(char *) a) - (*(char *) b);
}

char *getResult(char s[]) {
    int len &#61; strlen(s);

    char minS[len &#43; 1];
    strcpy(minS, s);

    qsort(minS, len, sizeof(char), cmp);

    if (strcmp(minS, s) &#61;&#61; 0) {
        return s;
    }

    for (int i &#61; 0; i &lt; len; i&#43;&#43;) {
        if(s[i] !&#61; minS[i]) {
            char tmp &#61; s[i];
            s[i] &#61; minS[i];

            int swapIdx &#61; strrchr(s, minS[i]) - s;
            s[swapIdx] &#61; tmp;
            break;
        }
    }

    return s;
}</code></pre> 
<p></p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>